<?php

class AuthController extends Controller
{

    public $baseUrl;
    public $layout = '_login';
    public function init(){
        $assets = Yii::getPathOfAlias('static').DIRECTORY_SEPARATOR.'backend'.DIRECTORY_SEPARATOR;
        //在asset中建立一个不冲突文件夹
        $this->baseUrl = Yii::app()->assetManager->publish($assets, false, -1, YII_DEBUG);
    }
    /**
     * 声明基于类的行为
     */
    public function actions()
    {
        return array(
            //captcha action renders the CAPTCHA image displayed on the contact page
            'captcha'=>array(
                'class'=>'CCaptchaAction',
                'backColor'=>0xFFFFFF,//背景颜色
                'minLength'=>4,//最短4位
                'maxLength'=>4,//最长四位
                //'class'=>'CaptchaExtendedAction',
                //'mode'=>CaptchaExtendedAction::MODE_DEFAULT,
                'offset'=>3,        //设置字符偏移量
                'testLimit'=>999,
            ),
            'page'=>array(
                'class'=>'CViewAction',
            ),
        );
    }
//    //验证管理员
//    public function actionCheckManager(){
//        if(Yii::app()->request->isAjaxRequest){
//            $username = Yii::app()->request->getParam('manager');
//            $password = Yii::app()->request->getParam('password');
//
//
//
//
//        }else{
//            Xtutuquan::redirect_message('非法操作','error',2);
//        }
//    }
    /**
     * @return  用户登录方法
     */
    public function actionLogin(){
        $user_login = new LoginForm;
        //是否是ajax验证
        if(isset($_POST['ajax']) && $_POST['ajax'] === 'login-form'){
            echo CActiveForm::validate($user_login);
            Yii::app()->end();
        }

        // 收集用户输入的数据
        if(Yii::app() -> request -> isPostRequest)
        {
            //用户锁定时间  分钟
            $time = Yii::app()->params['lockUserLoginTime'];
            $user_login->attributes=$_POST['LoginForm'];
            //检测是否被登录限制
            if(parent::_cookiesGet('adminLogin')) {
                //上分钟了
                if(parent::_cookiesGet('adminLogin')-time() > 60){
                    $lockTime = ceil((parent::_cookiesGet('adminLogin')-time())/60);
                    $timeLang = '分钟后尝试';
                }else{
                    $lockTime = parent::_cookiesGet('adminLogin')-time();
                    $timeLang = '秒后尝试';
                }
                parent::_backendLogger(array ('catalog' => 'login' , 'intro' => '账户已被锁定:' . $user_login->username , 'user_id' => 0 ));
                $this -> redirect_message('您的账号已锁定,请过'.$lockTime.$timeLang, 'error', 1, Yii::app() -> createUrl('auth/login'));
            }

            //用户信息进行session存储login()方法
            // 证用户输入  如果有效则重定向到前一页
            //如果登录验证都成功则跳转 $model->validate() && && $user_login->login()
            if($user_login->validate() && $user_login->login()){
                //写入log
                $userid = Yii::app()->user->id;
                $count = Manage::model()->updateAll(array('logintimes'=>Yii::app()->user->getState('loginnum')+1),'admin_id=:pass',array(':pass'=>$userid));
                parent::_backendLogger(array ('catalog' => 'login' , 'intro' => '用户登录成功:'.$user_login->username ));
                $this->redirect(Yii::app()->user->returnUrl);
            }else{
                //失败
                if (Yii::app()->session['errorAdminLogin']) {
                    $error = intval(Yii::app()->session['errorAdminLogin']) - 1;
                    if($error <=1){
                        //删除session的值
                        unset(Yii::app()->session['errorAdminLogin']);
                        //设置cookie
                        $cookie = new CHttpCookie('adminLogin',time()+$time*60);
                        $cookie->expire = time()+$time*60; //时间
                        Yii::app()->request->cookies['adminLogin']=$cookie;
                    } else {
                        Yii::app()->session['errorAdminLogin'] = $error;
                    }
                } else {
                    //用户输入错误最大数
                    $error = Yii::app()->params['userErrorMax'];
                    Yii::app()->session['errorAdminLogin'] = $error;
                }
                //登录失败了
                parent::_backendLogger(array ('catalog' => 'login' , 'intro' => '登录失败，密码不正确:' . $user_login->username. '，使用密码：'.$user_login->password , 'user_id' => 0 ));
                $this -> redirect_message('用户名或密码错误,您还可以尝试'.$error.'次', 'error', 1, Yii::app() -> createUrl('auth/login'));
            }
        }
        //显示登陆表单
        $this->render('login',array('user_login'=>$user_login,'baseUrl'=>$this->baseUrl));
    }

    /**
     * 注销当前用户和重定向到主页
     */
    public function actionLogout()
    {
        Yii::app()->user->logout();
        $this->redirect(Yii::app()->homeUrl);
    }
    /**
     * 这是方法来处理外部异常.
     */
    public function actionError()
    {
        if($error=Yii::app()->errorHandler->error)
        {
            if(Yii::app()->request->isAjaxRequest)
                echo $error['message'];
            else
                $this->render('error', $error);
        }
    }

}